package com.lfm.friend.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lfm.core.constants.HttpConstants;
import com.lfm.core.enums.ResultCode;
import com.lfm.core.enums.UserIdentity;
import com.lfm.core.enums.UserStatus;
import com.lfm.friend.domain.User;
import com.lfm.friend.domain.dto.UserDTO;
import com.lfm.friend.mapper.UserMapper;
import com.lfm.friend.service.IUserService;
import com.lfm.security.exception.ServiceException;
import com.lfm.security.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private TokenService tokenService;

    @Value("jwt.secret")
    private String secret;

    @Override
    public String login(String phone, String password) {
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>()
                .eq(User::getPhone, phone));
        if(user == null){   //新用户
            //注册逻辑
            user = new User();
            user.setPhone(phone);
            user.setPassword(password);
            user.setStatus(UserStatus.Normal.getValue());
            userMapper.insert(user);
        }
        String userPassword = user.getPassword();
        if(!userPassword.equals(password)){
            throw new ServiceException(ResultCode.FAILED_PHONE_LOGIN);
        }
        //密码比对成功
        return tokenService.createToken(user.getUserId(), secret, UserIdentity.ORDINARY.getValue(), user.getNickName());

    }

    @Override
    public boolean logout(String token) {
        if (StrUtil.isNotEmpty(token) && token.startsWith(HttpConstants.PREFIX)) {
            token = token.replaceFirst(HttpConstants.PREFIX, StrUtil.EMPTY);
        }
        return tokenService.deleteLoginUser(token, secret);
    }
}
